package com.dream.dynamic_datasource.ServiceForChangeDb.impl;

import com.dream.dynamic_datasource.dynamic.DynamicDataSource;
import com.dream.dynamic_datasource.dynamic.DynamicDataSourceContextHolder;
import com.dream.dynamic_datasource.entity.user.Db;
import com.dream.dynamic_datasource.mapper.DataSourceMapper;
import com.dream.dynamic_datasource.ServiceForChangeDb.DBChangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:
 * @author: Luo
 * @create: 2020-08-25 16:05
 */
@Service
public class DBChangeServiceImpl implements DBChangeService {
    @Autowired
    private DataSourceMapper dataSourceMapper;
    @Autowired
    private DynamicDataSource dynamicDataSource;
    @Override
    public List<Db> get() {
        return dataSourceMapper.get();
    }

    @Override
    public boolean changeDb(String dbName) throws Exception {
        //默认切换到主数据源,进行整体资源的查找
        DynamicDataSourceContextHolder.removeDataSourceRouterKey();

        List<Db> dataSourcesList = dataSourceMapper.get();

        for (Db dataSource : dataSourcesList) {
            if ((dataSource.getDbName()).equals(dbName)) {
                System.out.println("需要使用的的数据源已经找到,dbName：" + dbName);
                //创建数据源连接&检查 若存在则不需重新创建
                dynamicDataSource.createDataSourceWithCheck(dataSource);
                //切换到该数据源
                DynamicDataSourceContextHolder.setDataSourceRouterKey(dbName);
                return true;
            }
        }
        return false;

    }

}
